package com.navidove.commons.utils;

import java.beans.PropertyEditorSupport;
import java.io.Serializable;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.navidove.commons.dao.Dao;

@Component
public class DaoPropertyEditor extends PropertyEditorSupport {
	
	private static DaoPropertyEditor instance; 
	
	@Autowired
	ApplicationContext applicationContext;
		    
    private Dao<Serializable, Serializable> dao;
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static DaoPropertyEditor getInstance(Class<? extends  Dao> clazz) {
    	return new DaoPropertyEditor(instance.applicationContext.getBean(clazz));
    }
    
    public DaoPropertyEditor() {
    	instance = this;
    }
    
    private DaoPropertyEditor(Dao<Serializable, Serializable> dao){
        this.dao = dao;
    }
    
    public void setAsText(String text) throws IllegalArgumentException {
        Serializable bo = null;
        if (StringUtils.isNotBlank(text)){
            Serializable id;
            try {
                id = dao.getPrimaryKeyClass().getConstructor(String.class).newInstance(text);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
            bo = dao.get(id);
        }
        setValue(bo);
    }

    /**
     * @see java.beans.PropertyEditorSupport#getAsText()
     */
    public String getAsText() {
        Object value = getValue();
        if (value == null)
            return null;
        try {
        	return PropertyUtils.getProperty(value, "id").toString();
        } catch (Exception e) {
        	//throw new IllegalStateException(e);
        }
        return null;
    }
}
